package com.springboot.chongwu.controller.sys;


import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.springboot.chongwu.entity.SysManager;
import com.springboot.chongwu.entity.req.SysManagerReq;
import com.springboot.chongwu.entity.search.SysManagerSearch;
import com.springboot.chongwu.entity.view.SysManagerView;
import com.springboot.chongwu.qpage.QPage;
import com.springboot.chongwu.service.ISysManagerService;
import com.springboot.chongwu.util.ResultView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 后台账户表 前端控制器
 * </p>
 *
 * @author lbk
 * @since 2021-10-19
 */
@RestController
@RequestMapping("/api/admin/manager")
public class SysManagerController {

    @Autowired
    private ISysManagerService iSysManagerService;


    /**
     * 用户列表
     * @return
     */
    @GetMapping("/list")
    public ResultView list(QPage qPage, SysManagerSearch sysManagerSearch) {
        SysManager sysManager=this.iSysManagerService.getById(StpUtil.getLoginIdAsString());
        if(sysManager.getMType()!=1){
            sysManagerSearch.setParentManagerId(sysManager.getManagerId());
        }
        return this.iSysManagerService.getListAll(qPage,sysManagerSearch);
    }


    /**
     * 账号详情
     * @param managerId
     * @return
     */
    @GetMapping("/getManagerId")
    public ResultView getManagerId(@NotNull(message = "账户ID不能为空") String managerId) {
        return this.iSysManagerService.getManagerId(managerId);
    }


    /**
     * 新增账号
     * @param hjManagerReq
     * @return
     */
    @PostMapping("/addManager")
    public ResultView addManager(@Validated SysManagerReq hjManagerReq) {
        return this.iSysManagerService.addManager(hjManagerReq);
    }

    /**
     * 修改用户
     * @param hjManagerReq
     * @return
     */
    @PostMapping("/updateManager")
    public ResultView updateManager(@Validated SysManagerReq hjManagerReq) {
        return this.iSysManagerService.updateManager(hjManagerReq);
    }



    /**
     * 启用或者禁用用户
     * @param managerId
     * @return
     */
    @PostMapping("/applyStatus")
    public ResultView applyStatus(@NotNull(message = "账户ID不能为空") String managerId) {
        return this.iSysManagerService.applyStatus(managerId);
    }


    /**
     * 删除用户
     * @param managerId
     * @return
     */
    @PostMapping("/deleteManager")
    public ResultView deleteManager(@NotNull(message = "账户ID不能为空") String managerId) {
        return this.iSysManagerService.deleteManager(managerId);
    }

    /**
     * 重置密码
     * @param mPwd
     * @return
     */
    @PostMapping("/restPwd")
    public ResultView restPwd(@NotNull(message = "旧密码不能为空") String mPwd,
                              @NotNull(message = "新密码不能为空") String newPwd,
                              @NotNull(message = "二次确认新密码不能为空") String aginPwd) {
        if(!newPwd.equals(aginPwd)){
            return ResultView.error("两次密码不一致");
        }
        return this.iSysManagerService.restPwd(mPwd,newPwd);
    }


    /**
     * 上传修改头像
     * @return
     */
    @PostMapping("/updateImgUrl")
    public ResultView updateImgUrl(String imgUrl) {
        //进行登录认证
        String managerId= StpUtil.getLoginIdAsString();
        SysManager sysManager=this.iSysManagerService.getById(managerId);
        sysManager.setMUrl(imgUrl);
        this.iSysManagerService.updateById(sysManager);
        return ResultView.ok();
    }


    /**
     *文件下载并且失败的时候返回json（默认失败了会返回一个有部分数据的Excel）
     * @since 2.1.1
     */
    @PostMapping("download")
    public void downloadFailedUsingJson(SysManagerSearch search, HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("账户列表", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            List<SysManagerView> deviceList=this.iSysManagerService.downLoadList(search);
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), SysManagerView.class).autoCloseStream(Boolean.FALSE).sheet("账户列表")
                    .doWrite(deviceList);
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = MapUtils.newHashMap();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }

    public static void main(String[] args) {
        StringBuffer stringBuffer=new StringBuffer();
        for(int i=0;i<=1;i++){
            stringBuffer.append("222").append(",");
        }
        System.out.println(stringBuffer.substring(0,stringBuffer.length()-1));
        String[] stringsToQuery = new String[]{"str1", "str2", "str3"};

        // 将字符串数组转换为List
        List<String> stringList = Arrays.asList(stringsToQuery);
        System.out.println(stringList);
    }

}
